package main

import (
	"fmt"
	"time"
	"bytes"
	"flag"
	"strconv"
	"io/ioutil"
	"net/http"
	"math/rand"
	"github.com/golang/snappy"
	"github.com/gogo/protobuf/proto"
	"github.com/prometheus/prometheus/prompb"
)

func GenerateRangeNum(min, max int) int {
	rand.Seed(time.Now().Unix())
	randNum := rand.Intn(max - min)
	randNum = randNum + min
	return randNum
}

var client = &http.Client{
	Transport: &http.Transport{},
}

func main(){
	url := flag.String("addr", "http://127.0.0.1:8480/insert/0/prometheus", "api address")
	flag.Parse()
	for {
		var ts []prompb.TimeSeries
		for i := 1; i <= 10000; i++ {
			labels := []prompb.Label{
				prompb.Label{
					Name: "__name__",
					Value: "cpu_used",
				},
				prompb.Label{
					Name: "cpu",
					Value: "cpu" + strconv.Itoa(i),
				},
			}
			samples := []prompb.Sample{
				prompb.Sample{
					Timestamp: time.Now().Unix() * 1000,
					Value: float64(GenerateRangeNum(1,100)),
				},
			}
			fmt.Println(samples)
			ts = append(ts, prompb.TimeSeries{
				Labels: labels,
				Samples: samples,
			})
		}

		//序列化 && 加密
		data, err := proto.Marshal(&prompb.WriteRequest{
			Timeseries: ts,
		})
		if err != nil{
			fmt.Println(err)
			return
		}
		compressed := snappy.Encode(nil, data)

		//发送
		req, err := http.NewRequest("POST", *url,  bytes.NewBuffer(compressed))
		if err != nil{
			fmt.Println(err)
			return
		}
		resp, err := client.Do(req)
		if err != nil {
			fmt.Println(err)
			return
		}
		defer resp.Body.Close()

		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(string(body))
		//time.Sleep(100*time.Millisecond)
	}

}
